package com.xh.demo.config.handler;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.xh.demo.commons.enums.MessageEnum;
import com.xh.demo.commons.model.response.R;
import com.xh.demo.commons.utils.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author wen
 * @apiNote 全局资源流控处理器
 * 对于使用了 {@link SentinelResource}注解的方法不会走此处理器，可以通过 blockHandler指定处理方法
 * @since 2021-12-11
 */
@Slf4j
@Component
public class MyBlockedExceptionHandler implements BlockExceptionHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
        log.info("【触发保护机制】【{}】【{}】【{}】【{}】", e.getRule().getResource(), e.getRule().getLimitApp(), request.getMethod(), request.getRequestURI());
        R<Void> r = R.build(MessageEnum.CODE_60004);
        if (e instanceof FlowException) {
            log.info("【接口限流】");
            r = R.build(MessageEnum.CODE_60001);
        } else if (e instanceof DegradeException) {
            log.info("【服务降级】");
            r = R.build(MessageEnum.CODE_60002);
        } else if (e instanceof ParamFlowException) {
            log.info("【热点参数限流】");
            r = R.build(MessageEnum.CODE_60003);
        } else if (e instanceof SystemBlockException) {
            log.info("【触发系统保护规则】");
            r = R.build(MessageEnum.CODE_60004);
        } else if (e instanceof AuthorityException) {
            log.info("【授权规则不通过】");
            r = R.build(MessageEnum.CODE_60005);
        }
        ResponseUtil.write(r, response);
    }

}
